﻿using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEditor.Callbacks;
using UnityEngine;

namespace com.yd.sdk
{
    public class PaySetting : ISetting
    {
        private bool _isUseGoogleBilling;

        public void Init()
        {
            _isUseGoogleBilling = SDKEditorWindow.sdkSettings.isOpen_Google_Billing;
        }

        public void OnGUI()
        {
            GUILayout.Label("支付SDK模块");
            GUILayout.BeginHorizontal();
            _isUseGoogleBilling = GUILayout.Toggle(_isUseGoogleBilling, "开启GoogleBilling");
            
            GUILayout.EndHorizontal();
        }

        public void Apply()
        {
            if (_isUseGoogleBilling)
            
                InstallGoogleBilling();

                //打开
                //UnityEditor.PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android,true);
                // bool mobileMTRendering = UnityEditor.PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android);
                //Debug.Log("-------------------><color=#ff0000> Test: " + context + "</color><-------------------");
            else
                RemoveGoogleBilling();
            SDKEditorWindow.sdkSettings.isOpen_Google_Billing = _isUseGoogleBilling;
        }

        public bool IsSelectedSomething()
        {
            return _isUseGoogleBilling;
        }
        
        private void InstallGoogleBilling()
        {
            //向Gradle中添加依赖库
            Utils.MergeDependenciesInGradle(Constants.GetFullPath(Constants.ANDROID_MAIN_TEMPLATE_PATH),
                Constants.BILLINGS_DEPENDENCIES);
            
            //添加权限
            Utils.MergeAndroidManifest(Constants.GetFullPath(Constants.GOOGLE_BILLING_MANIFEST, true),
                Constants.GetFullPath(Constants.ANDROID_MAIN_MANIFEST));
            
            //添加实现包
            // FileUtil.ReplaceFile(Constants.GetFullPath(Constants.GOOGLE_BILLING_IMP, true),
            //     Constants.GetFullPath(Constants.GOOGLE_BILLING_PATH));
            
            Utils.MergeDependenciesInGradle(Constants.GetFullPath(Constants.ANDROID_MAIN_TEMPLATE_PATH),
                Constants.BILLINGS_IMP_DEPENDENCIES);
        }

        private void RemoveGoogleBilling()
        {
            Utils.DeleteStringFromFile(Constants.GetFullPath(Constants.ANDROID_MAIN_TEMPLATE_PATH),
                "\t" + Constants.BILLINGS_DEPENDENCIES + "\r");
            Utils.DeleteStringFromFile(Constants.GetFullPath(Constants.ANDROID_MAIN_TEMPLATE_PATH),
                "\t" + Constants.BILLINGS_IMP_DEPENDENCIES + "\r");
        }


#if UNITY_EDITOR
        [PostProcessBuild(100)]
        public static void OnPostProcessBuild(BuildTarget target, string pathToBuiltProject)
        {
            if (target == BuildTarget.Android)
            {
                
            }
        }
    }
        
#endif     
        
   
    
}